<?php
define("KEY_PRIVATE", "
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCpvdExvx5zybwFboU1NSjuIghiuXNQSNiJ27G8iETbJdhtibKv
TlbyzBVhq0brhnG16MG29pf8055zwODYKpWC+hPVJTflzhcYEVEqRpstq9q2BHe7
5ErRgjYIQiNGZJ11czQUj82TgDP3xMKntpchel5J3XbYfGjMzG3nARoOpwIDAQAB
AoGAa42A3hqReyCaaH6tHRfABZO+6H9Fl9twiXmRVzqpFosWZeHYPMhQw6uY6LgU
Sex4ZKFFDV+W0nZsckAGuDHTZY+j9mrmz+DJLknBFSqIr29T4bPRDEkCKgQSALAE
Xu3XRDeichbQPbg1D79Stisg74Exu4w96cRiKUb4Gv4UeUECQQDf3rqH1Cf/ILZT
TWfVGknOYAITWXWrcgOGfetZElYlIoDdV0hMK9+JZFRNTODUcbftuEm0Fzssof5J
CoDPYkzRAkEAwhpWA3vQ/u4zXWED4QnGFsqnd1V8WUiKrKYxfQowNndUhEOXeSoz
cx0RoSTJZkzzEsAJRftGpRXwuJHbgmsh9wJASM6lF3u2LlEzOtBXzoSoMEglJKnZ
jRKdduYI3oUKIzWfd1zllHBIWOSaTjGMhUseqF9hCQLtKczdaF/UGJ49oQJAGLEi
+gR5PMTukdVymeEVavbSwPKGBBGfWoE10HNIWNVrUfwLO+Wrb9xlzrsQR8xIK710
MIvbm8qjuccMRpX8VwJBAJ7J8s0A7MBuKu89esWw0Rx6lkxy2cmHqOT4h1yN2HTV
WgygOJ/d+KdmPBoPeLI4cMj7hmH243hZcrN0qF9Q9BE=
-----END RSA PRIVATE KEY-----
");

//解密方法
function decrypt($msg){
    $decrypted = "";
    
    openssl_private_decrypt(base64_decode($msg),$decrypted,KEY_PRIVATE);//私钥解密  
    return $decrypted;  
}


function apisCommonRedis(){
    $redis = new \Redis();
    $redis->connect('127.0.0.1',getenv('REDIS_PORT'));
    return $redis;
}
//获取客服账号信息
function customer_info(){
    $customer_info = [
        'kefu01'=>6382,
        'kefu02'=>6382,
        'kefu03'=>6382,
        'kefu04'=>6382,
        'haiyang'=>20381353,
    ];
    return $customer_info;
}

function getNextValue($array, $currentValue) {
    $keys = array_keys($array);
    $currentKey = array_search($currentValue, $array);

    if ($currentKey !== false){
        $currentIndex = array_search($currentKey, $keys);
        $nextIndex = $currentIndex + 1;

        // 处理循环（最后一个取第一个）
        if (!isset($keys[$nextIndex])) {
            reset($array);
            return current($array);
        }
        return $array[$keys[$nextIndex]];
    }
    return null;
}

function getParamArr($ParamStr){
    
    if(!$ParamStr){
        $ParamStr = 'z';
    }
    
    $ParamStr = $_REQUEST[$ParamStr];

    $pattern = "/\[([^=]+)=\{\{(.*?)\}\}\]/";

    preg_match_all($pattern, $ParamStr,$match);

    $Params = array();
    for($i=0;$i<count($match[1]);$i++){
        $Params[$match[1][$i]] = strval($match[2][$i]);
    }

    return $Params;
}
function getPostParamArr($ParamStr){

    if(!$ParamStr){
        $ParamStr = 'z';
    }

    $ParamStr = urldecode($_POST[$ParamStr]);
    $pattern = "/\[([^=]+)=\{\{(.*?)\}\}\]/";

    preg_match_all($pattern, $ParamStr,$match);

    $Params = array();
    for($i=0;$i<count($match[1]);$i++){
        $Params[$match[1][$i]] = strval($match[2][$i]);
    }

    return $Params;
}

//解开参数
function getRsaPostParamArr($ParamStr){

    if(!$ParamStr){
        $ParamStr = 'z';
    }

    $ParamStr = decrypt($_POST[$ParamStr]);

    $pattern = "/\[([^=]+)=\{\{(.*?)\}\}\]/";

    preg_match_all($pattern, $ParamStr,$match);

    $Params = array();
    for($i=0;$i<count($match[1]);$i++){
        $Params[$match[1][$i]] = strval($match[2][$i]);
    }

    return $Params;
}

function getSuccessJson($list,$errorname=''){
    $JsonArr = array();
    $JsonPrefix = strtolower(CONTROLLER_NAME."_".ACTION_NAME);
    
    $JsonArr["code"] = 200;
    $JsonArr["result"] = array();
    if($errorname){
        $JsonArr["errorname"] = $errorname;
    }else{
        $JsonArr["errorname"] = "操作失败";
    }
    if(sizeof($list) == 1){
    	if($list[0] == null){
    	   $JsonArr['result']=[];
    	   return json_encode($JsonArr,JSON_UNESCAPED_UNICODE);
    	}else{
    	   $JsonArr['result']=$list[0];
    	   return json_encode($JsonArr,JSON_UNESCAPED_UNICODE);
    	}
    }
    foreach ($list as $key => $value){
        if(!is_numeric($key)){
            $JsonArr["result"][$key] = $value;
        }
    }
    
    foreach ($list as $key => $value){
        if(is_numeric($key)){
            $key = $JsonPrefix."_list".(intval($key)+1);
            $JsonArr["result"][$key] = $value;
        }
    }
    return json_encode($JsonArr,JSON_UNESCAPED_UNICODE);
}

function getErrorJson($error,$errorname){
    $JsonArr = array();
    $JsonPrefix = strtolower(CONTROLLER_NAME."_".ACTION_NAME);

    if($error){
        $JsonArr["error"] = $error;
    }else{
        $JsonArr["error"] = "10001";
    }
    if($errorname){
        $JsonArr["errorname"] = $errorname;
    }else{
        $JsonArr["errorname"] = "操作失败";
    }
    return json_encode($JsonArr,JSON_UNESCAPED_UNICODE);
}

//递归获取分级
function recursion($data,$id,$level){
	if($level == 5){
		return;
	}
	$list = array();
	foreach($data as $v){
		if($v['upper'] == $id){
			$v['son'] = recursion($data,$v['lower'],++$level);
			if(empty($v['son'])) {
			   unset($v['son']);
			}
			array_push($list, $v);
		}
		
	}
	return $list;
}

$list = array();

//递归获取上级
function getUpper($data,$id){
	foreach($data as $v){
		if($v['lower'] == $id){
			array_push($list,$v['upper']);
			if(sizeof($list)<3){
			   getUpper($data,$v['upper']);
			}
			break;
		}
	}
}

function getlist(){
	return $list;
}

function extend_1($file_name) 
{ 
	$retval=""; 
	$pt=strrpos($file_name, "."); 
	if ($pt) $retval=substr($file_name, $pt+1, strlen($file_name) - $pt); 
	return ($retval); 
} 

function assoc_unique($arr, $key) {    
	$tmp_arr = array();   
	foreach($arr as $k => $v) {   
		if(in_array($v[$key], $tmp_arr)) {   
			unset($arr[$k]);   
		} else {   
			$tmp_arr[] = $v[$key];   
		}   
	}   
	sort($arr);   
	return $arr;   
}   
 //计算时间
 function time_tran($the_time,$re_time='') {
    $now_time = date("Y-m-d H:i:s", time());  
    //echo $now_time;  
    $now_time = strtotime($now_time);  
    $show_time = strtotime($the_time);  
    $dur = $now_time - $show_time;  
	
    if ($dur < 0) {  
        return $the_time;  
    } else {  
        if ($dur < 60) {  
            return $dur . '秒前';  
        } else {  
            if ($dur < 3600) {  
                return floor($dur / 60) . '分钟前';  
            } else {  
                if ($dur < 86400) {  
                    return floor($dur / 3600) . '小时前';  
                } else {  
                   
                    return floor($dur / 86400) . '天前';  
                   
                }  
            }  
        }  
    }  
}  

function convertSpecialNumbers($str) {
    $mapping = [
        '①' => '1',
        '②' => '2',
        '③' => '3',
        '④' => '4',
        '⑤' => '5',
        '⑥' => '6',
        '⑦' => '7',
        '⑧' => '8',
        '⑨' => '9',
        '⑩' => '10',
        '❶' => '1',
        '❷' => '2',
        '❸' => '3',
        '❹' => '4',
        '❺' => '5',
        '❻' => '6',
        '❼' => '7',
        '❽' => '8',
        '❾' => '9',
        '❿' => '10',
        '⒈' => '1',
        '⒉' => '2',
        '⒊' => '3',
        '⒋' => '4',
        '⒌' => '5',
        '⒍' => '6',
        '⒎' => '7',
        '⒏' => '8',
        '⒐' => '9',
        '⒑' => '10',
        '🄁' => '0',
        '🄂' => '1',
        '🄃' => '2',
        '🄄' => '3',
        '🄅' => '4',
        '⒌' => '5',
        '🄇' => '6',
        '⒎' => '7',
        '🄉' => '8',
        '🄊' => '9',
        '⚀' => '1',
        '⚁' => '2',
        '⚂' => '3',
        '⚃' => '4',
        '⚄' => '5',
        '⚅' => '6',
        '⑴' => '1',
        '⑵' => '2',
        '⑶' => '3',
        '⑷' => '4',
        '⑸' => '5',
        '⑹' => '6',
        '⑺' => '7',
        '⑻' => '8',
        '⑼' => '9',
        '⑽' => '10',
        '㈠' => '1',
        '㈡' => '2',
        '㈢' => '3',
        '㈣' => '4',
        '㈤' => '5',
        '㈥' => '6',
        '㈦' => '7',
        '㈧' => '8',
        '㈨' => '9',
        '㈩' => '10',
        'ⅰ' => '1',
        'ⅱ' => '2',
        'ⅲ' => '3',
        'ⅳ' => '4',
        'ⅴ' => '5',
        'ⅵ' => '6',
        'ⅶ' => '7',
        'ⅷ' => '8',
        'ⅸ' => '9',
        'ⅹ' => '10',
        'Ⅰ' => '1',
        'Ⅱ' => '2',
        'Ⅲ' => '3',
        'Ⅳ' => '4',
        'Ⅴ' => '5',
        'Ⅵ' => '6',
        'Ⅶ' => '7',
        'Ⅷ' => '8',
        'Ⅸ' => '9',
        'Ⅹ' => '10',
        'Ⅺ' => '11',
        'Ⅻ' => '12',
        '⁰' => '0',
        '¹' => '1',
        '²' => '2',
        '³' => '3',
        '⁴' => '4',
        '⁵' => '5',
        '⁶' => '6',
        '⁷' => '7',
        '⁸' => '8',
        '⁹' => '9',
        '₀' => '0',
        '₁' => '1',
        '₂' => '2',
        '₃' => '3',
        '₄' => '4',
        '₅' => '5',
        '₆' => '6',
        '₇' => '7',
        '₈' => '8',
        '₉' => '9',
    ];

    return strtr($str, $mapping);
}

function is_hasNumber($val){
    $val = convertSpecialNumbers($val);

    $state = false;
    preg_match_all("/\d+/",$val,$arr);
    for ($i=0; $i < sizeof($arr); $i++) { 
        for ($j=0; $j < sizeof($arr[$i]); $j++) {
            if(strlen($arr[$i][$j]) > 0){
                $state = true;
            }
        }
    }
    return $state;
}
function isPhoneNumber($val){
    if(preg_match("/^1[3456789]{1}\d{9}$/",$val)){
        return true;
    }else{
        return false;
    }
}
function ishasPhoneNumber($val){
    $state = false;
    preg_match_all("/\d+/",$val,$arr);
    for ($i=0; $i < sizeof($arr); $i++) { 
        for ($j=0; $j < sizeof($arr[$i]); $j++) {
            if(strlen($arr[$i][$j]) > 10){
                $state = true;
            }
        }
    }
    return $state;
}

function is_hasCnNumber($val){
    $state = false;
    $arr = ["零","壹","貳","叁","肆","伍","陆","柒","捌","玖","拾","一","二","三","四","五","六","七","八","九","十"];
    foreach ($arr as $key => $value) {
        if(strpos($val,$value) !== false)
        {
            $state = true;
            break;
        }else{
            $state = false;
        }
    }
    return $state;
}

function is_emoji($content){
    $arrs = array("[微笑]","[撇嘴]","[色]","[发呆]","[得意]","[流泪]","[害羞]","[闭嘴]","[睡]","[大哭]","[尴尬]","[发怒]","[调皮]","[呲牙]","[惊讶]","[难过]","[酷]","[冷汗]","[抓狂]","[吐]","[偷笑]","[愉快]","[白眼]","[傲慢]","[饥饿]","[困]","[恐惧]","[流汗]","[憨笑]","[悠闲]","[奋斗]","[咒骂]","[疑问]","[嘘]","[晕]","[疯了]","[衰]","[骷髅]","[敲打]","[再见]","[擦汗]","[抠鼻]","[鼓掌]","[糗大了]","[坏笑]","[左哼哼]","[右哼哼]","[哈欠]","[鄙视]","[委屈]","[快哭了]","[阴险]","[亲亲]","[吓]","[可怜]","[菜刀]","[西瓜]","[啤酒]","[篮球]","[乒乓]","[咖啡]","[饭]","[猪头]","[玫瑰]","[凋谢]","[嘴唇]","[爱心]","[心碎]","[蛋糕]","[闪电]","[炸弹]","[刀]","[足球]","[瓢虫]","[便便]","[月亮]","[太阳]","[礼物]","[拥抱]","[强]","[弱]","[握手]","[胜利]","[抱拳]","[勾引]","[拳头]","[差劲]","[爱你]","[NO]","[OK]","[爱情]","[飞吻]","[跳跳]","[发抖]","[怄火]","[转圈]","[磕头]","[回头]","[跳绳]","[投降]","[激动]","[街舞]","[献吻]","[左太极]","[右太极]");
    
    foreach ($arrs as $key => $value) {
        $content = str_replace($value, "", $content);
    }
    if($content == ''){
        return true;
    }
    return false;
}


function getRoles($ids = '', $roles = [])
{
    $role = [];
    $ids = explode(',', $ids);
    foreach ($ids as $key => $value) {
        if (isset($roles[$value+1])) {
            $role[] = $roles[$value+1];
        }
    }
    return implode('|', $role);
}
/**
 * http get 请求
 *
 * @param string $url    请求地址
 * @param array  $header 请求头部
 *
 * @return array
 */
function http_get($url, $header = [])
{
    if (empty($header)) {
        $header = [
            "Content-type:application/json;",
            "Accept:application/json"
        ];
    }

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    $response = curl_exec($curl);
    curl_close($curl);
    $response = json_decode($response, true);

    return $response;
}

/**
 * 批量更新数据
 * @param string $table_name
 * @param array $data
 * @param string $field
 * @return bool|false|int
 */
function _db_batch_update($table_name='',$data=array(),$field=''){
    if(!$table_name||!$data||!$field){
        return false;
    }else{
        $sql='UPDATE '.$table_name;
    }
    $con=array();
    $con_sql=array();
    $fields=array();
    foreach ($data as $key => $value) {
        $x=0;
        foreach ($value as $k => $v) {
            if($k!=$field&&!$con[$x]&&$x==0){
                $con[$x]=" set {$k} = (CASE {$field} ";
            }elseif($k!=$field&&!$con[$x]&&$x>0){
                $con[$x]=" {$k} = (CASE {$field} ";
            }
            if($k!=$field){
                $temp=$value[$field];
                $con_sql[$x].= " WHEN '{$temp}' THEN '{$v}' ";
                $x++;
            }
        }
        $temp=$value[$field];
        if(!in_array($temp,$fields)){
            $fields[]=$temp;
        }
    }
    $num=count($con)-1;
    foreach ($con as $key => $value) {
        foreach ($con_sql as $k => $v) {
            if($k==$key&&$key<$num){
                $sql.=$value.$v.' end),';
            }elseif($k==$key&&$key==$num){
                $sql.=$value.$v.' end)';
            }
        }
    }
    $str=implode(',',$fields);
    $sql.=" where {$field} in({$str})";
    $res=M($table_name)->execute($sql);
    return $res;
}


    /**
     * http post 请求
     *
     * @param string $url    请求地址
     * @param array  $param  请求参数
     * @param array  $header 请求头部
     *
     * @return array
     */
    function http_post($url, $param = [], $header = [])
    {
        $param = json_encode($param);

        if (empty($header)) {
            $header = [
                "Content-type:application/json;charset='utf-8'",
                "Accept:application/json"
            ];
        }

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $param);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($curl);
        curl_close($curl);
        $response = json_decode($response, true);

        return $response;
    }